const util = require('../../utils/util.js');
const api = require('../../config/api.js');
const user = require('../../utils/user.js');

//获取应用实例
const app = getApp();

Page({
  data: {
    banner: [],
    purchaseList:[],
    searchValue:'',
  },

  onPullDownRefresh() {
    wx.showNavigationBarLoading() //在标题栏中显示加载
    this.getIndexData();
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新
  },

  getIndexData: function() {
    wx.showLoading({
      title: '加载中...',
    });
    let that = this;
    util.request(api.IndexUrl,{
      searchValue:that.data.searchValue
    }).then(function(res) {
      if (res.errno === 0) {
        // console.log(res.data.purchaseList)
        let purchaseList = res.data.purchaseList.map(item => {
          item.publishDt = util.formatTime2(new Date(item.publishDt),"Y/M/D");
          let time = 24*60*60*10;
          item.dueTime = item.dueSecond*1000<time ? time:item.dueSecond*1000;
          return item;
        });
        that.setData({
          banner: res.data.banner,
          purchaseList: purchaseList,
        });
      }
      wx.hideLoading();
    }).finally(() => {
      wx.hideLoading();
    });
  },
  viewMore(){
    wx.setStorageSync('purchase_type',1)
    wx.switchTab({
      url: "../purchase/purchase?type=1"
    });
  },
  openPurchase(event) {
    let that = this;
    let index = event.currentTarget.dataset.index;
    let purchase = this.data.purchaseList[index];
    // console.log(purchase)
    
    wx.setStorageSync('purchasesStr', JSON.stringify([purchase]));
    wx.navigateTo({
      url: `/pages/purchaseDetail/purchaseDetail?id=${purchase.id}&itemId=${purchase.itemId}`
    });
  },
  onChange(e) {
    this.setData({
      searchValue: e.detail,
    });
  },
  onSearch() {
    this.getIndexData();
  },
  onLoad: function(options) {
    this.getIndexData();
  },
  onReady: function() {
    // 页面渲染完成
  },
  onShow: function() {
    // 页面显示
  },
  onHide: function() {
    // 页面隐藏
  },
  onUnload: function() {
    // 页面关闭
  },
})